package com.takepoints21.mobile;

import com.takepoints.android.bo.Card;
import com.takepoints.android.services.TPServices;
import com.takepoints21.mobile.zxing.CaptureActivity;
import com.takepoints.android.util.DownloadImageTask;
import com.takepoints.android.util.StringUtil;
import com.takepoints.android.util.UserInterfaceUtil;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.ImageView.ScaleType;

public class MyCardDetail extends BaseActivity {
	
	private int cardId;
	private String siteName;
	private int totalOrng;
	
	private Card card = null;
	//private ImgOrangeAdapter orangeAdapter = null;
	private int density = DisplayMetrics.DENSITY_DEFAULT;
	
	private final String IMG_PATH = "https://www.takepoints.com/public/uploads/mobile/";
	private final String IMG_REWARD_PATH = "https://www.takepoints.com/public/uploads/reward/thumb/";
	
	public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mycarddetail);
        manageMenu(3);
        
		density = getResources().getDisplayMetrics().densityDpi;
        
        Bundle bundle = this.getIntent().getExtras();
    	cardId = Integer.parseInt(bundle.getString("cardId"));
        siteName = bundle.getString("siteName");
    	totalOrng  = (!StringUtil.isEmpty(bundle.getString("totalOrng"))?Integer.parseInt(bundle.getString("totalOrng")):-1);
        
        LinearLayout lnrContent = (LinearLayout)findViewById(R.id.lnrContent);
        lnrContent.getBackground().setAlpha(200);
        
        TextView lblHeader = (TextView)findViewById(R.id.lblHeader);
        if(siteName != null){
        	lblHeader.setText(siteName);
        }
    	processCardDetail();
	}
	
	@Override
	public void onBackPressed(){
		Intent myCardsInt = new Intent(this, MyCards.class);
		startActivityForResult(myCardsInt, 0);
		return;
	}
	
	private void processCardDetail(){
		final ProgressDialog dialog = ProgressDialog.show(this, "Takepoints.com", "Loading Detail ...", true);
		final Handler handler = new Handler() {
        	public void handleMessage(Message msg) {
        		if(card != null){
        			ImageView imgItem = (ImageView)findViewById(R.id.imgItem);
        			if(imgItem != null){
        				Bitmap bitmap = BitmapFactory.decodeFile(IMG_CACHE_PATH + card.getImageName());
        				if(bitmap != null){
        					imgItem.setImageBitmap(bitmap);
        				} else{
        					imgItem.setTag(IMG_PATH + card.getImageName());
            				new DownloadImageTask().execute(imgItem);
        				}
        			}
        			
        			TextView txtCardName = (TextView)findViewById(R.id.txtCardName);
        			txtCardName.setText(card.getItemName());
        			txtCardName.setTextColor(Color.parseColor("#555555"));
        			//txtCardName.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        			
	            	int star = Integer.parseInt(card.getStar().trim());
	            	int approved = Integer.parseInt(card.getApprove());
	            	
        			Button btnUse = (Button)findViewById(R.id.btnUse);
        			if(star > 0 && star == approved){
        				btnUse.setText("สะสมครบแล้ว");
        				btnUse.setTextColor(Color.parseColor("#fbca54"));
        				btnUse.setBackgroundColor(Color.DKGRAY);
        			} else{
	        			btnUse.setOnClickListener(new View.OnClickListener(){
				            public void onClick(View view){
			            		/*postToFacebook( "ได้รับผลส้มเพิ่ม ในบัตรสะสม " + card.getItemName()
	            				  , "Takepoints"
	            				  , "http://www.takepoints.com/"
	            				  , "Takepoints เหมาะสำหรับธุรกิจ และพฤติกรรมการใช้โทรศัพท์มือถือของลูกค้า เพื่อช่วยให้ธุรกิจต่างๆ ได้สร้างเคมเปญทางการตลาด"
	            				  , "http://www.takepoints.com/public/images/takepoint_bottom.jpg");
				            	*/
				            	gotoVerifyCode();
				            }
				        });
        			}
        			
        			LinearLayout lnrContent = (LinearLayout)findViewById(R.id.lnrContent);
        			
        			/* ======================= Calculate Oranges ======================= */
    				int total = 0;
    				if(card.getStar() != null){
    					total = Integer.parseInt(card.getStar().trim());
    				}
    				int appv = Integer.parseInt(card.getApprove());
    				int pend = Integer.parseInt(card.getPending());
    				//popup("appv = " + appv + " , pend = " + pend);
    				
    				int level1 = -1;
    				int level2 = -1;
    				int level3 = -1;
    				int added = 0;
    				if(!StringUtil.isEmpty(card.getLevel1())){
    					added++;
    					level1 = Integer.parseInt(card.getLevel1().trim());
    				}
    				if(!StringUtil.isEmpty(card.getLevel2())){
    					added++;
    					level2 = Integer.parseInt(card.getLevel2().trim()) + 1;
    				}
    				if(!StringUtil.isEmpty(card.getLevel3())){
    					added++;
    					level3 = Integer.parseInt(card.getLevel3().trim()) + 2;
    				}
    				
    		        Integer[] orangeIds = new Integer[total + added];
    		        for(int i=0; i<(total + added); i++){
    		        	if(i == level1){
    		        		orangeIds[i] = 1111;
    		        	} else if(i == level2){
    		        		orangeIds[i] = 2222;
    		        	} else if(i == level3){
    		        		orangeIds[i] = 3333;
    		        	} else{
    		        		if(appv > 0){
    		        			orangeIds[i] = R.drawable.orangeapprove;
    		        			--appv;
    		        			--pend;
    		        		} else if(pend > 0){
    		        			orangeIds[i] = R.drawable.orangepending;
    		        			--pend;
    		        		} else{
    		        			orangeIds[i] = R.drawable.orangestart;
    		        		}
    		        	}
    		        }
    		        /* ===================== End Calculate Oranges ===================== */
    		        
    		        GridView gridOrange = new GridView(lnrContent.getContext());
    		        gridOrange.setBackgroundResource(R.drawable.card_bg);
    		        if((total+added) > 12){
	    		        int remain = (total+added) - 12;
			        	int expand = remain>=6?((int)(remain / 6)):0;
			        	if((remain % 6) > 0){
			        		expand += 1;
			        	}
		        		
			        	//gridOrange.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 166+(84*expand)));
			        	if(density >= 320){
				        	gridOrange.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 249+(126*expand)));
						} else if(density >= DisplayMetrics.DENSITY_HIGH){
				        	gridOrange.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 166+(84*expand)));
						} else if(density >= DisplayMetrics.DENSITY_MEDIUM){
				        	gridOrange.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 111+(56*expand)));
						} else{		// DisplayMetrics.DENSITY_LOW
				        	gridOrange.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 66+(34*expand)));
						}
		        	} else{
						//gridOrange.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 166));
		        		int dp = UserInterfaceUtil.pixel2dp(density, 166);
		        		gridOrange.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT, dp ));
		        	}
    		        gridOrange.setPadding(5, 4, 5, 4);
    		        gridOrange.setNumColumns(GridView.AUTO_FIT);
    		        gridOrange.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
    		        gridOrange.setHorizontalSpacing(8);
    		        gridOrange.setVerticalSpacing(7);
    		        gridOrange.setColumnWidth(63);
    		        
    		        ImgOrangeAdapter orangeAdapter = new ImgOrangeAdapter(gridOrange.getContext());
    		        orangeAdapter.setOrangesStatus(orangeIds);
    		        gridOrange.setAdapter(orangeAdapter);
    		        
    		        lnrContent.addView(gridOrange);
    		        
    		        
    		        TableRow tr1 = new TableRow(lnrContent.getContext());
        	    	tr1.setBackgroundResource(R.drawable.info_middle);
        	    	TableRow.LayoutParams tr1Param = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 50);
        	    	tr1Param.setMargins(1, 8, 1, 4);
        	    	tr1.setLayoutParams(tr1Param);
	        	    	TextView txtExpiryDate = new TextView(tr1.getContext());
	        	    	txtExpiryDate.setText("ภายในวันที่  " + card.getEndDate());
	        	    	txtExpiryDate.setTextSize(13);
	        	    	txtExpiryDate.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
	        	    	txtExpiryDate.setTextColor(Color.parseColor("#555555"));
	        	    	txtExpiryDate.setMinimumHeight(42);
	        	    	txtExpiryDate.setPadding(5, 3, 5, 3);
	        	    	txtExpiryDate.setGravity(Gravity.CENTER_VERTICAL);
	        	    tr1.addView(txtExpiryDate);
	        	    lnrContent.addView(tr1);
    				
				    TableRow tr2 = new TableRow(lnrContent.getContext());
        	        tr2.setBackgroundResource(R.drawable.info_middle);
        	    	TableRow.LayoutParams tr2Param = new TableRow.LayoutParams( TableRow.LayoutParams.FILL_PARENT
        	    															  , TableRow.LayoutParams.WRAP_CONTENT);
        	    	tr2Param.setMargins(1, 4, 1, 6);
        	    	tr2.setLayoutParams(tr2Param);
	        	        TextView txtOfferLine1 = new TextView(tr2.getContext());
	        	        txtOfferLine1.setText(StringUtil.nvl(card.getOfferLine1(), StringUtil.BLANK));
	        	        txtOfferLine1.setTextSize(11);
	        	        txtOfferLine1.setTextColor(Color.GRAY);
	        	        txtOfferLine1.setHeight(LayoutParams.WRAP_CONTENT);
	        	        txtOfferLine1.setPadding(5, 3, 5, 3);
	        	        txtOfferLine1.setSingleLine(false);
	        	        txtOfferLine1.setGravity(Gravity.TOP);
	        	        tr2.addView(txtOfferLine1);
	        	    lnrContent.addView(tr2);
        		}
        		dialog.dismiss();
        	}
		};
        Thread thread = new Thread(){  
        	public void run(){
        		card = TPServices.getMyItemDetail(cardId);
        		handler.sendEmptyMessage(0);
        	}
        };
        thread.start();
	}
    
    private final void gotoVerifyCode(){
    	//Intent verifyInt = new Intent(this, VerifyCode.class);
    	Intent verifyInt = new Intent(this, CaptureActivity.class);
    	verifyInt.putExtra("cardId", card.getItemId());
    	verifyInt.putExtra("siteName", siteName);
    	verifyInt.putExtra("pageSrc", "MyCardDetail");
    	startActivityForResult(verifyInt, 0);
    }
	
	public class ImgOrangeAdapter extends BaseAdapter {
    	private Context mContext;
    	
    	private Integer[] mThumbIds = {};
    	//{ R.drawable.orangeblank, R.drawable.orangestart , R.drawable.orangepending, R.drawable.orangeapprove };
    	
    	public ImgOrangeAdapter(Context c){
			mContext = c;
		}
    	
    	public void setOrangesStatus(Integer[] mThumbIds){
    		this.mThumbIds = mThumbIds;
    	}
    	
    	public View getView(final int position, View convertView, ViewGroup parent){
			 ImageView imageView = null;
			 
			 /*GridView.LayoutParams rewardGridParams = null;
			 if(density >= DisplayMetrics.DENSITY_XHIGH){
				 rewardGridParams = new GridView.LayoutParams(113, 113);
			 } else if(density >= DisplayMetrics.DENSITY_HIGH){
				 rewardGridParams = new GridView.LayoutParams(75, 75);
			 } else if(density >= DisplayMetrics.DENSITY_MEDIUM){
				 rewardGridParams = new GridView.LayoutParams(50, 50);
			 } else{		// DisplayMetrics.DENSITY_LOW
				 rewardGridParams = new GridView.LayoutParams(30, 30);
			 }*/
			 
			 if(mThumbIds[position] == 1111){
				 
				 if("Y".equalsIgnoreCase(card.getRewardedLev1())){
					 imageView = new ImageView(mContext){
						 @Override
						 public void onDraw(Canvas canvas) {
							 /*Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
							 p.setColor(Color.parseColor("#FF8E01"));
							 p.setStrokeWidth(2);
							 canvas.drawLine(0, 0, 75, 75, p);
							 canvas.drawLine(75, 0, 0, 75, p);*/
							 Paint p = new Paint();
							 //p.setARGB(255, 255, 255, 255);
							 p.setColor(Color.parseColor("#FF8E01"));
							 //p.setTextAlign(Paint.Align.CENTER);
						     p.setTextSize(24);
						     canvas.drawText("แลก", 20, 20, p);
						     canvas.drawText("แล้ว", 20, 45, p);
						     canvas.rotate((int)(32 * 180 / Math.PI), getWidth() >> 1, getHeight() >> 1);
						     super.onDraw(canvas);
						 }
					 };
					 imageView.setBackgroundColor(Color.parseColor("#FF8E01"));
					 imageView.setAlpha(150);
					 
				 } else{
					 imageView = new ImageView(mContext);
					 if(Integer.parseInt(card.getApprove()) >= Integer.parseInt(card.getLevel1())){
						 imageView.setBackgroundColor(Color.parseColor("#FF8E01"));
						 imageView.setOnClickListener(new View.OnClickListener(){
				            public void onClick(View view){
				            	Intent myCardRewardInt = new Intent(view.getContext(), MyCardRewardDetail.class);
				            	myCardRewardInt.putExtra("cardId", card.getItemId());
				            	myCardRewardInt.putExtra("promotionId", card.getPromotionId());
				            	myCardRewardInt.putExtra("rewardNum", card.getLevel1());
				            	startActivityForResult(myCardRewardInt, 0);
				            }
				        });
					 } else{
						 imageView.setAlpha(100);
					 }
				 }
				 int rewardGridDP = UserInterfaceUtil.pixel2dp(density, 75);
				 imageView.setLayoutParams( new GridView.LayoutParams(rewardGridDP, rewardGridDP) );
				 
				 Bitmap bitmap = BitmapFactory.decodeFile(IMG_CACHE_PATH + card.getImgLevel1());
				 if(bitmap != null){
					 imageView.setImageBitmap(bitmap);
				 } else{
					 imageView.setTag(IMG_REWARD_PATH + card.getImgLevel1());
					 new DownloadImageTask().execute(imageView);
				 }
				 
			 } else if(mThumbIds[position] == 2222){
				 
				 if("Y".equalsIgnoreCase(card.getRewardedLev2())){
					 imageView = new ImageView(mContext){
						 @Override
						 public void onDraw(Canvas canvas) {
							 Paint p = new Paint();
							 p.setColor(Color.parseColor("#FF8E01"));
						     p.setTextSize(24);
						     canvas.drawText("แลก", 20, 20, p);
						     canvas.drawText("แล้ว", 20, 45, p);
						     canvas.rotate((int)(32 * 180 / Math.PI), getWidth() >> 1, getHeight() >> 1);
						     super.onDraw(canvas);
						 }
					 };
					 imageView.setBackgroundColor(Color.parseColor("#FF8E01"));
					 imageView.setAlpha(150);
					 
				 } else{
					 imageView = new ImageView(mContext);
					 if(Integer.parseInt(card.getApprove()) >= Integer.parseInt(card.getLevel2())){
						 imageView.setBackgroundColor(Color.parseColor("#FF8E01"));
						 imageView.setOnClickListener(new View.OnClickListener(){
				            public void onClick(View view){
				            	Intent myCardRewardInt = new Intent(view.getContext(), MyCardRewardDetail.class);
				            	myCardRewardInt.putExtra("cardId", card.getItemId());
				            	myCardRewardInt.putExtra("promotionId", card.getPromotionId());
				            	myCardRewardInt.putExtra("rewardNum", card.getLevel2());
				            	startActivityForResult(myCardRewardInt, 0);
				            }
				        });
					 } else{
						 imageView.setAlpha(100);
					 }
				 }
				 int rewardGridDP = UserInterfaceUtil.pixel2dp(density, 75);
				 imageView.setLayoutParams( new GridView.LayoutParams(rewardGridDP, rewardGridDP) );
				 
				 Bitmap bitmap = BitmapFactory.decodeFile(IMG_CACHE_PATH + card.getImgLevel2());
				 if(bitmap != null){
					 imageView.setImageBitmap(bitmap);
				 } else{
					 imageView.setTag(IMG_REWARD_PATH + card.getImgLevel2());
					 new DownloadImageTask().execute(imageView);
				 }
				 
			 } else if(mThumbIds[position] == 3333){
				 
				 if("Y".equalsIgnoreCase(card.getRewardedLev3())){
					 imageView = new ImageView(mContext){
						 @Override
						 public void onDraw(Canvas canvas) {
							 Paint p = new Paint();
							 p.setColor(Color.parseColor("#FF8E01"));
						     p.setTextSize(24);
						     canvas.drawText("แลก", 20, 20, p);
						     canvas.drawText("แล้ว", 20, 45, p);
						     canvas.rotate((int)(32 * 180 / Math.PI), getWidth() >> 1, getHeight() >> 1);
						     super.onDraw(canvas);
						 }
					 };
					 imageView.setBackgroundColor(Color.parseColor("#FF8E01"));
					 imageView.setAlpha(150);
					 
				 } else{
					 imageView = new ImageView(mContext);
					 if(Integer.parseInt(card.getApprove()) >= Integer.parseInt(card.getLevel3())){
						 imageView.setBackgroundColor(Color.parseColor("#FF8E01"));
						 imageView.setOnClickListener(new View.OnClickListener(){
				            public void onClick(View view){
				            	Intent myCardRewardInt = new Intent(view.getContext(), MyCardRewardDetail.class);
				            	myCardRewardInt.putExtra("cardId", card.getItemId());
				            	myCardRewardInt.putExtra("promotionId", card.getPromotionId());
				            	myCardRewardInt.putExtra("rewardNum", card.getLevel3());
				            	startActivityForResult(myCardRewardInt, 0);
				            }
				        });
					 } else{
						 imageView.setAlpha(100);
					 }
				 }
				 int rewardGridDP = UserInterfaceUtil.pixel2dp(density, 75);
				 imageView.setLayoutParams( new GridView.LayoutParams(rewardGridDP, rewardGridDP) );
				 
				 Bitmap bitmap = BitmapFactory.decodeFile(IMG_CACHE_PATH + card.getImgLevel3());
				 if(bitmap != null){
					 imageView.setImageBitmap(bitmap);
				 } else{
					 imageView.setTag(IMG_REWARD_PATH + card.getImgLevel3());
					 new DownloadImageTask().execute(imageView);
				 }
				 
			 } else{
				 int gridDP = UserInterfaceUtil.pixel2dp(density, 65);
				 
				 imageView = new ImageView(mContext);
				 imageView.setLayoutParams(new GridView.LayoutParams(gridDP, gridDP));
				 imageView.setImageResource(mThumbIds[position]);
			 }
			 imageView.setScaleType(ScaleType.FIT_XY);
			 imageView.setPadding(2, 2, 2, 2);
			 
			 return imageView;
    	}
    	
    	@Override
		public int getCount(){
			return mThumbIds.length;
		}
    	@Override
		public Object getItem(int arg0){
			return null;
		}
		@Override
		public long getItemId(int position){
			return position;
		}
	}
	
	/*private final class WallPostListener extends BaseRequestListener {
		@Override
		public void onComplete(String response, Object state) {
			mRunOnUi.post(new Runnable() {
				@Override
				public void run() {
					mProgress.cancel();
					Toast.makeText(MyCardDetail.this, "Posted to Facebook", Toast.LENGTH_SHORT).show();
				}
			});
		}
	}*/
	
}
